import cv2, time
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QFileDialog

from gui import *


class ui(Ui_Dialog):
    def __init__(self):
        super(ui, self).__init__()
        self.timer_camera = QtCore.QTimer()
        self.cap = cv2.VideoCapture()
        self.CAM_NUM = 0
        self.__flag_work = 0
        self.x = 0
        self.count = 0
        self.dic = None

    def setupUi(self, Dialog):
        super(ui, self).setupUi(Dialog)
        Dialog.setWindowTitle(u'摄像头')
        self.open.clicked.connect(self.open_cam)
        self.timer_camera.timeout.connect(self.show_camera)
        self.close.clicked.connect(exit)
        self.setpath.clicked.connect(self.set_path)
        self.save_b.clicked.connect(self.save)
        self.path.setReadOnly(True)
        self.path.clear()

    def open_cam(self):
        if not self.timer_camera.isActive():
            flag = self.cap.open(self.CAM_NUM)
            if not flag:
                msg = QtWidgets.QMessageBox.warning(widget, u"Warning", u"请检测相机与电脑是否连接正确",
                                                    buttons=QtWidgets.QMessageBox.Ok,
                                                    defaultButton=QtWidgets.QMessageBox.Ok)
            else:
                self.open.setText('关闭')
                self.timer_camera.start(1)

        else:
            self.open.setText('打开')
            self.timer_camera.stop()
            self.cap.release()
            self.label.clear()

    def show_camera(self):
        flag, self.image = self.cap.read()
        show = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
        # print(show.shape[1], show.shape[0])
        # show.shape[1] = 640, show.shape[0] = 480
        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
        self.label.setPixmap(QtGui.QPixmap.fromImage(showImage))

    def set_path(self):
        self.dic = QFileDialog.getExistingDirectory(widget, "选择文件夹", "D:/")
        self.path.setText(self.dic)

    def save(self):
        if self.dic is not None:
            print(self.dic)
            show = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
            showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
            QtGui.QPixmap.fromImage(showImage).save(f"{self.dic}/{time.time()}.jpg", "JPG")
        else:
            self.set_path()
            self.save()


def exit():
    sys.exit(0)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    widget = QtWidgets.QWidget()
    ui_S = ui()
    ui_S.setupUi(widget)
    # ui.run_before()
    widget.setWindowIcon(QIcon('web.ico'))
    widget.show()
    sys.exit(app.exec_())
